
var CART_DETAIL_URL = "/index.php/checkout/cart/";
function checkQuota(ProductID, MenuID, Quantity) {
    return true;
}

//Khoi tao gio hang
function initCart() {
    var cart = [];
    if (localStorage["OVI-CART"] != null) {
        cart = JSON.parse(localStorage.getItem("OVI-CART"));
    }
    var totalPrice = 0;
    for (var i = 0; i < cart.length; i++) {
        totalPrice += cart[i].itemPrice * cart[i].quantity;
    }
    $("#total-price").append(totalPrice + " VND");
    $("#total-price-summary").append(totalPrice + " VND");
    var totalQuantity = 0;
    for (var i = 0; i < cart.length; i++) {
        totalQuantity += cart[i].quantity;
    }
    $("#total-quantity-cart").append(totalQuantity);
    $("#total-quantity-cart-detail").append("Trong giỏ (" + totalQuantity + "sản phẩm)");
    var htmlItem = "";
    for (var i = 0; i < cart.length; i++) {
        var productID = cart[i].itemID;
        var productName = cart[i].itemName;
        var productQuantity = cart[i].quantity;
        var productIcon = cart[i].itemIcon;
        var productPrice = cart[i].itemPrice;

        htmlItem += "<li><div class='clearfix'><img class='f_left m_right_10' src='" + productIcon + "'>"
                + "<div class='f_left product_description'><p class='color_dark m_bottom_5 d_block'>" + productName +
                "</p><span class='f_size_medium'>Mã sản phẩm:" + productID + "</span></div>"
                + "<div class='f_left f_size_medium'><div class='clearfix' id='cart-price-" + productID + "'>" + productQuantity + "x <b class='color_dark'>" + productPrice + "</b> VNĐ</div>"
                + "<button class='close_product color_dark tr_hover'><i class='fa fa-times'></i></button></div></div></li>";
    }
    $("#cart-menu-item").html(htmlItem);
}

function addToCart(productID) {

    var flagIsExsit = false;
    var cart = [];
    if (localStorage["OVI-CART"] != null) {
        cart = JSON.parse(localStorage.getItem("OVI-CART"));
    }

    for (var i = 0; i < cart.length; i++) {
        var item = cart[i];
        //console.log("pp" + productID);
        if (item.itemID == productID) {
            flagIsExsit = true;
            if (item.quantity < 10) {
                item.quantity++;
                var newHtmlPrice = item.quantity + "x <b class='color_dark'>" + item.itemPrice + "</b> VNĐ";
                $("#cart-price-" + item.itemID).html(newHtmlPrice);
            } else {
                alert("Số lượng mọi món phải nhỏ hơn 10!");
            }
            break;
        }
    }
    if (!flagIsExsit) {
        var productIcon = $("#product-icon-" + productID).attr("src");
        var productPrice = $("#product-item-price-" + productID).attr("data-price");
        var productName = $("#product-name-" + productID).attr("data-name");
        var item = {itemID: productID, itemName: productName, quantity: 1, itemIcon: productIcon, itemPrice: productPrice};
        cart.push(item);

        var htmlItem = "<li><div class='clearfix'><img class='f_left m_right_10' src='" + productIcon + "'>"
                + "<div class='f_left product_description'><p class='color_dark m_bottom_5 d_block'>" + productName +
                "</p><span class='f_size_medium'>Mã sản phẩm:" + productID + "</span></div>"
                + "<div class='f_left f_size_medium'><div class='clearfix' id='cart-price-" + productID + "'> 1 x <b class='color_dark'>" + productPrice + "</b> VNĐ</div>"
                + "<button class='close_product color_dark tr_hover'><i class='fa fa-times'></i></button></div></div></li>";
        $("#cart-menu-item").append(htmlItem);
    }

    if (localStorage["OVI-CART"] != null) {

        var totalQuantity = 0;
        for (var i = 0; i < cart.length; i++) {
            totalQuantity += cart[i].quantity;
        }

        $("#total-quantity-cart").html(totalQuantity);
        $("#total-quantity-cart-detail").html("Trong giỏ (" + totalQuantity + "sản phẩm)");

        var totalPrice = 0;
        for (var i = 0; i < cart.length; i++) {
            totalPrice += cart[i].itemPrice * cart[i].quantity;
        }

        $("#total-price").html(totalPrice + " VND");
        $("#total-price-summary").html(totalPrice + " VND");
    } else {

        $("#total-quantity-cart").html(1);
        $("#total-quantity-cart-detail").html("Trong giỏ (1 sản phẩm)");
        $("#total-price").html(productPrice + " VND");
        $("#total-price-summary").html(productPrice + " VND");
    }

    localStorage.setItem("OVI-CART", JSON.stringify(cart));

    //window.location.href = CART_DETAIL_URL;
}


function initCartDetail() {

    var cart = [];
    if (localStorage["OVI-CART"] != null) {
        cart = JSON.parse(localStorage.getItem("OVI-CART"));


        var htmlItem = "";
        for (var i = 0; i < cart.length; i++) {

            var productID = cart[i].itemID;
            var productName = cart[i].itemName;
            var productQuantity = cart[i].quantity;
            var productIcon = cart[i].itemID;
            var productPrice = cart[i].itemPrice;

            htmlItem += "<tr><td style='min-width:500px'><img style='float:left;width:80px' src='" + urlimg + productIcon + ".jpg' /><p style='text-transform:uppercase;font-size:20px;margin-top:10px'>" + productName + "</p></td>"
                    + "<td>" + productQuantity + "</td><td>" + productPrice + "</td><td>" + productPrice * productQuantity + "</td></tr>";
        }

        $("#cart-detail-product-list").html(htmlItem);


        var totalPrice = 0;
        for (var i = 0; i < cart.length; i++) {
            totalPrice += cart[i].itemPrice * cart[i].quantity;
        }
        $("#total-price-detail").append(totalPrice + " VND");
        $("#total-price-summary-detail").append(totalPrice + " VND");
    } else {
        $("#cart-detail-page").html("<h1 style='margin-top:200px;text-align:center;'>Chưa có sản phẩm trong giỏ hàng.</h1><div style='margin-left:40%;margin-bottom:200px !important;margin-top:30px'><a href='/index.php/welcome/' style='font-size:24px;'>Tiếp tục mua hàng.</a></div>");
    }
}

function updateCart(productID) {
    var value = $("#quanlity-item-" + productID).val();
    var cart = [];
    if (localStorage["OVI-CART"] != null) {
        cart = JSON.parse(localStorage.getItem("OVI-CART"));
    }

    for (var i = 0; i < cart.length; i++) {
        var item = cart[i];
        if (item.itemID == productID) {
            if (value == 0) {

                $("#add-button-" + productID).removeClass("active-btn");

                var totalItem = parseInt($("#number-of-cart-item").html().trim());
                totalItem -= item.quantity;
                $("#number-of-cart-item").html(totalItem);

                var totalPrice = parseInt($("#total-price").html().trim());
                totalPrice -= item.quantity * parseInt($("#price-cart-item-" + productID).html().trim());
                $("#total-price").html(totalPrice);

                $("#item-" + productID).remove();
                cart.splice(i, 1);

                $("#dish-in-cart-" + productID).html(0);
                $("#dish-in-cart-" + productID).css("z-index", -1);
                $("#dish-in-cart-" + productID).css("opacity", 0);
                $("#dish-in-cart-details-" + productID).css("opacity", 0);
                $("#dish-in-cart-details-" + productID).html(0);

                if (cart.length < 4) {
                    $("#control-cart").remove();
                }

                $("#slider-cart").css("left", 0);
                currentSlider = 1;

                if (cart.length == 0) {
                    showNoneFace('2', 1);
                    $("#price-table").css("visibility", "hidden");
                }

            } else {
                if (checkQuota(productID, item.menuID, value)) {
                    var totalItem = parseInt($("#number-of-cart-item").html().trim());
                    totalItem += (value - item.quantity);
                    $("#number-of-cart-item").html(totalItem);

                    var totalPrice = parseInt($("#total-price").html().trim());
                    totalPrice += (value - item.quantity) * parseInt($("#price-cart-item-" + productID).html().trim());
                    $("#total-price").html(totalPrice);

                    item.quantity = value;
                    $("#dish-in-cart-" + productID).html(item.quantity);
                    $("#dish-in-cart-details-" + productID).html(item.quantity);
                } else {
                    $("#quanlity-item-" + productID).val(item.quantity);
                    alert("Đã hết sản phẩm!");
                }
            }
            break;
        }
    }

    localStorage.setItem("OVI-CART", JSON.stringify(cart));
}
function initcheckout() {
    var cart = [];
    if (localStorage["OVI-CART"] != null) {
        cart = JSON.parse(localStorage.getItem("OVI-CART"));

        // var masp = "";
        var soluong = 0;

        var linkBaoKim = "";
        for (var i = 0; i < cart.length; i++) {

            var productID = cart[i].itemID;
            var productName = cart[i].itemName;
            var productQuantity = cart[i].quantity;
            //var productIcon = cart[i].itemID;
            var productPrice = cart[i].itemPrice;
            var order_description = "aaaa";
            soluong += cart[i].quantity;
            //masp += cart[i].itemID;

//            htmlItem += "<tr><td style='min-width:500px'><img style='float:left;width:80px' src='" +urlimg+ productIcon + ".jpg' /><p style='text-transform:uppercase;font-size:20px;margin-top:10px'>" + productName + "</p></td>"
//                    + "<td>" + productQuantity + "</td><td>" + productPrice + "</td><td>" + productPrice * productQuantity + "</td></tr>";

        }
        //$("#lstmasp").val(masp);
        // $("#lstsoluong").val(soluong);

        // $("#cart-detail-product-list").html(htmlItem);

        var totalPrice = 0;
        for (var i = 0; i < cart.length; i++) {
            totalPrice += cart[i].itemPrice * cart[i].quantity;
        }
        $("#total-price-detail").append(totalPrice + " VND");
        $.ajax({
            type: "POST",
            url: globalurl + "index.php/checkout/order",
            data: {
                'ordel_total': totalPrice
            }, success: function(data, status) {
                alert(data.result);

            }, error: function(data, status) {
                alert(status);
                alert(data);
            }

        });
        $.ajax({
            type: "POST",
            url: globalurl + "index.php/checkout/order_detail",
            data: {
                'productID': product_id,
                'productQuantity': qty,
                'productPrice': product_price
                
            }, success: function(data, status) {
                alert(data.result);

            }, error: function(data, status) {
                alert(status);
                alert(data);
            }

        });

        $("#total-price-summary-detail").append(totalPrice + " VND");
        linkBaoKim += "https://www.baokim.vn/payment/order/version11/" + "?business=snowstar.uit@gmail.com" + "&product_quantity=" + soluong + "&total_amount=" + totalPrice + "&url_cancel=http://localhost/ovitimeshop/index.php/checkout/cancel" + "&url_success=http://localhost/ovitimeshop/index.php/checkout/success";
        // alert(linkBaoKim);
        $("#btn-tt-baokim").click(function() {
            window.location = linkBaoKim;
        });
    }
}